/******************************************************************************* 
 * Copyright (C) 2012-2015 Microfountain Technology, Inc. All Rights Reserved. 
 * 
 * Unauthorized copying of this file, via any medium is strictly prohibited.   
 * Proprietary and confidential
 * 
 * Last Modified: 2015-9-22 17:29:02
 ******************************************************************************/
package cn.cmcc.online.smsapi.sdk.net.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import cn.cmcc.online.smsapi.sdk.constant.Constant;
import cn.cmcc.online.smsapi.sdk.db.entity.IccidInfo;
import cn.cmcc.online.smsapi.sdk.db.entity.SceneRule;
import cn.cmcc.online.smsapi.sdk.db.entity.Sceneconfig;
import cn.cmcc.online.smsapi.sdk.db.entity.SysParamEntityManager;
import cn.cmcc.online.smsapi.sdk.log.LogManager;
import cn.cmcc.online.smsapi.sdk.util.StringUtils;
import cn.cmcc.online.smsapi.sdk.util.XmlManager;

public class ServerResposeParseUtil {

    
    public static Map<String, Object> parseJarsUpdateRespose(String xml) {
        Map<String, Object> dataMap = null;// 返回结果
        JSONArray updataJars = null;// 返回需要更新包的信息集合
        JSONObject updateJar = null;// 返回需要更新的单个包信息
        String jars = "";// 更新的Jar包
        String jarVersion = "";// Jar包版本号，多个用逗号隔开（顺序与jars对应）
        String downLoadUrl = "";// Jar包下载地址，多个用逗号隔开（顺序与jars对应）
        String pver = "";// pver版本号，多个用逗号隔开（顺序与jars对应）
        String[] jarsArr = null;
        String[] jarVersionArr = null;
        String[] downLoadUrlArr = null;
        String[] pverArr = null;
        String emVersion = "";// 紧急信息版本号
        String emContent = "";// 紧急信息
        long delayStart = 0;
        long delayEnd = 0;

        try {
            Document doc = StringUtils.stringConvertXML(xml, "");
            if(doc==null)return null;
            Element root = doc.getDocumentElement();

            // 获取紧急信息
            NodeList enList = null;
            enList = root.getElementsByTagName("em");

            // 需要更新的包名
            jars = getNodeText(root, "jars");

            // 需要更新的包的版本
            jarVersion = getNodeText(root, "jarVersion");

            // 需要更新的包的下载地址
            downLoadUrl = getNodeText(root, "downLoadUrl");
            
            pver = getNodeText(root, "pver");

            // 信息为空的,则返回空
            if ((StringUtils.isNull(jars) || StringUtils.isNull(jarVersion))
                    && (enList == null || enList.getLength() == 0)) {
                return null;
            }

            dataMap = new HashMap<String, Object>();// 整合返回的数据集合

            long maxEmVersion = -1;
            if (enList != null && enList.getLength() > 0) {
            	JSONArray emergencyArray = new JSONArray();

            	for(int i=0;i<enList.getLength();i++){
            		 JSONObject jsonObject = new JSONObject();
            		 Node node = enList.item(i);
            	     emContent = XmlManager.getTextContent(node);
                     emVersion = ((Element)node).getAttribute("version");
                     jsonObject.put("emContent", emContent);
                     jsonObject.put("emVersion", emVersion);
                     try {
                    	if(!StringUtils.isNull(emVersion)){
    						long tempVerion = Long.parseLong(emVersion);
    						if(maxEmVersion<tempVerion)
    						{
    							maxEmVersion = tempVerion; 
    						}

                    	}
						
                     } catch (Throwable e) {
						LogManager.e(Constant.TAG, "parseJarsUpdateRespose ", e);
                     }
                     emergencyArray.put(jsonObject);
            	}
           
//                dataMap.put("emVersion", emVersion);
//                dataMap.put("emContent", emContent);
            	
            	SysParamEntityManager.setParam(
                        "EM_VERSION", maxEmVersion+"");
            	 dataMap.put("emergencyArray", emergencyArray);
            	
            }
            if (StringUtils.isNull(jars) || StringUtils.isNull(jarVersion)) {
                return dataMap;
            }

            jarsArr = jars.split(",");
            jarVersionArr = jarVersion.split(",");
            downLoadUrlArr = downLoadUrl.split(",");
            pverArr = pver.split(",");
            // 不对应,则返回空
            if (jarsArr.length != jarVersionArr.length
                    || jarVersionArr.length != downLoadUrlArr.length) {
                return dataMap;
            }

            // 更新延迟时间段开始
            String delayStartContent = getNodeText(root, "delaystart");
            if (!StringUtils.isNull(delayStartContent)) {
                delayStart = Long.parseLong(delayStartContent);
            }

            // 更新延迟时间段结束
            String delayEndContent = getNodeText(root, "delayend");
            if (!StringUtils.isNull(delayEndContent)) {
                delayEnd = Long.parseLong(delayEndContent);
            }
            if (delayEnd <= 0) {
                delayEnd = 3600 * 24 * 1000;
            }

            updataJars = new JSONArray();
            for (int i = 0; i < jarsArr.length; i++) {
                updateJar = new JSONObject();
                updateJar.put("name", jarsArr[i]);
                updateJar.put("version", jarVersionArr[i]);
                updateJar.put("url", downLoadUrlArr[i]);
                if(pverArr.length>i){
                    updateJar.put("pver", pverArr[i]);
                }
                updateJar.put("delayStart", delayStart);
                updateJar.put("delayEnd", delayEnd);
                updataJars.put(updateJar);
            }

            dataMap.put("updataJars", updataJars);
        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "parseJarsUpdateRespose: ", e);

        }
        return dataMap;
    }

    /***
     * 查询iccid的信息 rstCode 0：服务端无数据 1：服务端有数据 2：更新成功
     * ***/
    public static int parseQueryIccidInfoResponse(String xml, IccidInfo info) {
        int resCode = -1;
        try {
            Document doc = StringUtils.stringConvertXML(xml, "");
            if(doc==null)return -1;
            Element root = doc.getDocumentElement();
            resCode = Integer.parseInt(getNodeText(root, "rstCode"));
            if (resCode == 1) {
                info.iccid = getNodeText(root, "iccid");
                info.operator = getNodeText(root, "operator");
                info.provinces = getNodeText(root, "provinces");
                info.city = getNodeText(root, "city");
                info.updateTime = Long
                        .parseLong(getNodeText(root, "updateTime"));
            }
        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "parseQueryIccidInfoResponse: ", e);

        }
        return resCode;
    }

    private static String getNodeText(Element root, String tag) {
        NodeList list = null;
        list = root.getElementsByTagName(tag);
        if (list != null && list.getLength() > 0) {
            return XmlManager.getTextContent(list.item(0));
        }
        return "";
    }

    public static List<SceneRule> parseQuerySceneRuleResponse(String xml) {
        List<SceneRule> sceneconfigList = new ArrayList<SceneRule>();
        try {

            /*
             * <QuerySceneRuleResponse> <SceneRuleList> <SceneRule> <id>
             * 标识：由于一个情景ID,可能存在多条记录（有不同的规则）。 所以需要此标识唯一标识此记录 </id>
             * <sceneId>情景ID</sceneId> <sceneRuleVersion>版本号</sceneRuleVersion>
             * <province> 省份代表支持所有， 多个省份之间以;分隔 </province> <operator>运营商 1:联通
             * 2：电信 3：移动代表支持所有， 多个运营商之间以;分隔 </operator> <expire_date>代表没有日期限制
             * 日期-日期：两日期之间-日期：终止日期 日期- ：起始日期之后 <expire_date>
             * <fun_call><fun_call> <fun_acc_url>fun_acc_url>
             * <fun_reply_sms><fun_reply_sms> <fun_config><fun_config>
             * <res_urls><res_urls> <s_version><s_version> <scene_page_conf>
             * <scene_page_conf> <extend> <extend> <SceneRule> 多个......
             * <SceneRuleList> </QuerySceneRuleResponse>
             */

            Document doc = StringUtils.stringConvertXML(xml, "");
            if(doc==null)return null;
            NodeList items = doc.getElementsByTagName("SceneRule");
            for (int i = 0; i < items.getLength(); i++) {
                SceneRule sceneconfig = new SceneRule();
                Element skinNode = (Element) items.item(i);
                NodeList childsNodes = skinNode.getChildNodes();
                for (int j = 0; j < childsNodes.getLength(); j++) {
                    Node node = childsNodes.item(j); // 判断是否为元素类型
                    if (node.getNodeType() == Node.ELEMENT_NODE) {
                        String tagName = node.getNodeName();
                        if ("sceneId".equalsIgnoreCase(tagName)) {
                            sceneconfig.scene_id = XmlManager
                                    .getTextContent(node);
                        } else if ("sceneRuleVersion".equalsIgnoreCase(tagName)) {
                            sceneconfig.sceneruleVersion = XmlManager
                                    .getTextContent(node);
                        } else if ("province".equalsIgnoreCase(tagName)) {
                            sceneconfig.province = XmlManager
                                    .getTextContent(node);
                        } else if ("id".equalsIgnoreCase(tagName)) {
                            sceneconfig.id = XmlManager.getTextContent(node);
                        } else if ("operator".equalsIgnoreCase(tagName)) {
                            sceneconfig.operator = XmlManager
                                    .getTextContent(node);
                        } else if ("expire_date".equalsIgnoreCase(tagName)) {
                            sceneconfig.expire_date = XmlManager
                                    .getTextContent(node);
                        } else if ("fun_call".equalsIgnoreCase(tagName)) {
                            sceneconfig.Func_call = Integer.parseInt(XmlManager
                                    .getTextContent(node));
                        } else if ("fun_acc_url".equalsIgnoreCase(tagName)) {
                            sceneconfig.Func_acc_url = Integer
                                    .parseInt(XmlManager.getTextContent(node));
                        } else if ("fun_reply_sms".equalsIgnoreCase(tagName)) {
                            sceneconfig.Func_reply_sms = Integer
                                    .parseInt(XmlManager.getTextContent(node));
                        } else if ("fun_config".equalsIgnoreCase(tagName)) {
                            sceneconfig.Func_config = XmlManager
                                    .getTextContent(node);
                        } else if ("res_urls".equalsIgnoreCase(tagName)) {
                            sceneconfig.res_urls = XmlManager
                                    .getTextContent(node);
                        } else if ("s_version".equalsIgnoreCase(tagName)) {
                            sceneconfig.s_version = XmlManager
                                    .getTextContent(node);
                        } else if ("scene_page_conf".equalsIgnoreCase(tagName)) {
                            sceneconfig.Scene_page_config = XmlManager
                                    .getTextContent(node);
                        }

                    }

                }
                sceneconfigList.add(sceneconfig);

            }

        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "parseQuerySceneRuleResponse: ", e);

            // LogManager.e("result ", "error Throwable ="+e.getMessage());
        }
        return sceneconfigList;

    }

    public static boolean parseQueryIccidSceneResponseResultCode(String xml) {
        String sceneid = "";
        try {
            Document doc = StringUtils.stringConvertXML(xml, "");
            if(doc==null)return false;
            Element root = doc.getDocumentElement();
            NodeList list = null;
            list = root.getElementsByTagName("rstCode");
            if (list != null && list.getLength() > 0) {
                sceneid = XmlManager.getTextContent(list.item(0)).toString();

                if (!StringUtils.isNull(sceneid) && sceneid.equals("0")) {
                    return true;
                }
            }
        } catch (Throwable e) {
            // TODO: handle Throwable

        }
        return false;

    }

    public static boolean parseSceneCountActionResponseResultCode(String xml) {
        String sceneid = "";
        try {
            Document doc = StringUtils.stringConvertXML(xml, "");
            if(doc==null)return false;
            Element root = doc.getDocumentElement();
            NodeList list = null;
            list = root.getElementsByTagName("rstCode");
            if (list != null && list.getLength() > 0) {
                sceneid = XmlManager.getTextContent(list.item(0)).toString();

                if (!StringUtils.isNull(sceneid) && sceneid.equals("0")) {
                    return true;
                }
            }
        } catch (Throwable e) {
            // TODO: handle Throwable

        }
        return false;

    }

    public static HashMap<String, Object> parseQuerySceneRecordResponse(
            String xml) {
        HashMap<String, Object> result = new HashMap<String, Object>();
        ArrayList<Sceneconfig> sceneconfigList = new ArrayList<Sceneconfig>();
        try {

            /*
             * 接口响应协议： <QuerySceneRecordResponse> <SceneList> <Scene>
             * <sceneId>情景ID</sceneId> <sceneVersion>情景版本</sceneVersion>
             * <SceneRule> <id> 标识：由于一个情景ID,可能存在多条记录（有不同的规则）。 所以需要此标识唯一标识此记录
             * </id> <sceneId>情景ID</sceneId>
             * <sceneruleVersion>记录版本号</sceneruleVersion> <province> 省份代表支持所有，
             * 多个省份之间以;分隔 </province> <operator>运营商 1:联通 2：电信 3：移动代表支持所有，
             * 多个运营商之间以;分隔 </operator> <expire_date>代表没有日期限制 日期-日期：两日期之间-日期：终止日期
             * 日期- ：起始日期之后 <expire_date> <fun_call><fun_call>
             * <fun_acc_url>fun_acc_url> <fun_reply_sms><fun_reply_sms>
             * <fun_config><fun_config> <res_urls><res_urls>
             * <s_version><s_version> <scene_page_conf> <scene_page_conf>
             * <extend> <extend> </SceneRule> 一个情景，多个SceneRule...... <Secne>
             * 多个...... <SceneList> </QuerySceneRecordResponse>
             */

            Document doc = StringUtils.stringConvertXML(xml, "");
            if(doc==null)return null;
            // LogManager.i("parse", "parseQuerySceneRecordResponse xml="+xml);

            NodeList items = doc.getElementsByTagName("Scene");
            for (int i = 0; i < items.getLength(); i++) {
                Sceneconfig sceneconfig = new Sceneconfig();
                Element skinNode = (Element) items.item(i);
                NodeList childsNodes = skinNode.getChildNodes();
                for (int j = 0; j < childsNodes.getLength(); j++) {
                    Node node = childsNodes.item(j); // 判断是否为元素类型
                    if (node.getNodeType() == Node.ELEMENT_NODE) {
                        String tagName = node.getNodeName();
                        if ("sceneId".equalsIgnoreCase(tagName)) {
                            sceneconfig.sceneId = XmlManager
                                    .getTextContent(node);
                        } else if ("sceneVersion".equalsIgnoreCase(tagName)) {
                            sceneconfig.sceneVersion = XmlManager
                                    .getTextContent(node);
                        }
                    }

                }

                NodeList sceneRuleList = skinNode
                        .getElementsByTagName("SceneRule");
                if (sceneRuleList != null) {
                    int len = sceneRuleList.getLength();
                    for (int k = 0; k < len; k++) {
                        SceneRule sceneRule = new SceneRule();
                        Element sceneRuleEl = (Element) sceneRuleList.item(k);
                        NodeList sceneRuleNodes = sceneRuleEl.getChildNodes();
                        for (int l = 0; l < sceneRuleNodes.getLength(); l++) {
                            Node sceneRulenode = sceneRuleNodes.item(l); // 判断是否为元素类型
                            if (sceneRulenode.getNodeType() == Node.ELEMENT_NODE) {
                                String tagName = sceneRulenode.getNodeName();
                                if (sceneRulenode.getNodeType() == Node.ELEMENT_NODE) {
                                    if ("sceneId".equalsIgnoreCase(tagName)) {
                                        sceneRule.scene_id = XmlManager
                                                .getTextContent(sceneRulenode);
                                    } else if ("sceneRuleVersion"
                                            .equalsIgnoreCase(tagName)) {
                                        sceneRule.sceneruleVersion = XmlManager
                                                .getTextContent(sceneRulenode);
                                    } else if ("province"
                                            .equalsIgnoreCase(tagName)) {
                                        sceneRule.province = XmlManager
                                                .getTextContent(sceneRulenode);
                                    } else if ("id".equalsIgnoreCase(tagName)) {
                                        sceneRule.id = XmlManager
                                                .getTextContent(sceneRulenode);
                                    } else if ("operator"
                                            .equalsIgnoreCase(tagName)) {
                                        sceneRule.operator = XmlManager
                                                .getTextContent(sceneRulenode);
                                    } else if ("expire_date"
                                            .equalsIgnoreCase(tagName)) {
                                        sceneRule.expire_date = XmlManager
                                                .getTextContent(sceneRulenode);
                                    } else if ("fun_call"
                                            .equalsIgnoreCase(tagName)) {
                                        sceneRule.Func_call = Integer
                                                .parseInt(XmlManager
                                                        .getTextContent(sceneRulenode));
                                    } else if ("fun_acc_url"
                                            .equalsIgnoreCase(tagName)) {
                                        sceneRule.Func_acc_url = Integer
                                                .parseInt(XmlManager
                                                        .getTextContent(sceneRulenode));
                                    } else if ("fun_reply_sms"
                                            .equalsIgnoreCase(tagName)) {
                                        sceneRule.Func_reply_sms = Integer
                                                .parseInt(XmlManager
                                                        .getTextContent(sceneRulenode));
                                    } else if ("fun_config"
                                            .equalsIgnoreCase(tagName)) {
                                        sceneRule.Func_config = XmlManager
                                                .getTextContent(sceneRulenode);
                                    } else if ("res_urls"
                                            .equalsIgnoreCase(tagName)) {
                                        sceneRule.res_urls = XmlManager
                                                .getTextContent(sceneRulenode);
                                    } else if ("s_version"
                                            .equalsIgnoreCase(tagName)) {
                                        sceneRule.s_version = XmlManager
                                                .getTextContent(sceneRulenode);
                                    } else if ("scene_page_conf"
                                            .equalsIgnoreCase(tagName)) {
                                        sceneRule.Scene_page_config = XmlManager
                                                .getTextContent(sceneRulenode);
                                    }

                                }
                            }

                        }
                        sceneconfig.addSceneRule(sceneRule);
                    }
                }
                sceneconfigList.add(sceneconfig);

            }

            NodeList urls = doc.getElementsByTagName("SceneUrl");
            ArrayList<String> sceneUrllist = new ArrayList<String>();
            if (urls != null) {
                for (int i = 0; i < urls.getLength(); i++) {
                    String url = XmlManager.getTextContent(urls.item(i));
                    if (!StringUtils.isNull(url)) {
                        sceneUrllist.add(url);
                    }
                }
            }

            result.put("sceneUrllist", sceneUrllist);

        } catch (Throwable e) {
//            e.printStackTrace();
//            LogManager.e("result ", "error Throwable =" + e.getMessage(),e);
            LogManager.e(Constant.TAG, "parseQuerySceneRecordResponse: ", e);

        }
        result.put("sceneconfigList", sceneconfigList);

        return result;

    }

    /**
     * 解析返回的checkResourseResponse
     * 
     * @param xml
     * @return
     * 
     *         <checkResourseResponse> <code>状态码0:成功</code> <res_type>1:
     *         企业LOGO</res_type> <resItems> <res version=”资源版本号”
     *         del_history=”1有此属性说明需删除历史的所有资源文件及资源记录”>资源URL </res> <res
     *         version=”资源版本号”>资源URL </res > </resItems> </
     *         checkResourseResponse >
     */
    public static JSONArray parsecheckResourseResponse(String xml) {

        try {

            JSONArray jsonArray = new JSONArray();
            Document doc = StringUtils.stringConvertXML(xml, "");
            if(doc==null)return null;
            Element root = doc.getDocumentElement();
            NodeList list = null;
            list = root.getElementsByTagName("code");
            if (list != null && list.getLength() > 0) {
                String code = XmlManager.getTextContent(list.item(0))
                        .toString();
                if (StringUtils.isNull(code) || !"0".equals(code))
                    return null;
            }
            String res_type = "";
            list = root.getElementsByTagName("res_type");
            if (list != null && list.getLength() > 0) {
                res_type = XmlManager.getTextContent(list.item(0)).toString();
            }
            NodeList items = doc.getElementsByTagName("res");
            for (int i = 0; i < items.getLength(); i++) {
                JSONObject jsonObject = new JSONObject();
                Element skinNode = (Element) items.item(i);

                String version = skinNode.getAttribute("version");
                String del_history = skinNode.getAttribute("del_history");

                jsonObject.put("res_version", version);
                jsonObject.put("del_history", del_history);

                String res_url = XmlManager.getTextContent(skinNode);
                jsonObject.put("res_url", res_url);
                jsonObject.put("res_type", res_type);

                jsonArray.put(jsonObject);
            }

            return jsonArray;
        } catch (Throwable e) {
            // TODO: handle Throwable

        }
        return null;

    }

    public static JSONObject parseTrainData(String xml) {
        JSONObject jsonObject = null;
        try {
            Document doc = StringUtils.stringConvertXML(xml, "");
            if(doc==null)return null;
            Element root = doc.getDocumentElement();
            NodeList list = null;
            list = root.getElementsByTagName("data");
            if (list != null && list.getLength() > 0) {
                String dataStr = XmlManager.getTextContent(list.item(0))
                        .toString();
                if (!StringUtils.isNull(dataStr)) {
                    jsonObject = new JSONObject(dataStr);
                }
            }
        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "parseTrainData: ", e);

        }

        return jsonObject;
    }

}
